<template>
  <div id="editRole">
    <h3>编辑角色</h3>
    <!-- 角色信息 -->
    <Form :model="roleInfo">
        <FormItem label="角色名称">
            <Input v-model="roleInfo.rolename"></Input>
        </FormItem>
        <FormItem label="描述">
            <Input v-model="roleInfo.description"></Input>
        </FormItem>
    </Form>
    <!-- 权限树 -->
     <Tree ref="tree" :data="AllAuthority" show-checkbox></Tree>
    <Button type="primary" @click="saveRole(roleInfo.id)">保存修改</Button>
  </div>
</template>

<script>

export default {
  data(){
    return{
      roleInfo:{
        id:'',
        rolename:'',
        description:''
      },
      // 所有权限
      AllAuthority:[]
    }
  },
  created(){
    //获取用户的基本信息
    this.roleInfo.id = this.$route.query.role.id
    this.roleInfo.rolename = this.$route.query.role.rolename
    this.roleInfo.description = this.$route.query.description
    // console.log(this.$route.query.role)
    //获取用户的权限
    this.getAllAuthority()   
  },
  methods:{
    async getAllAuthority(){
      const {data:res} = await this.$axios.get('/menu/list/' + this.roleInfo.id)
      if(res.status == 200){
        for(let i = 0; i < res.data.length; i++){
          res.data[i].checked = false
          res.data[i].expand = true
        }
         console.log(res.data)
        this.AllAuthority = res.data
       
      }
      
      // res.data是权限
      // for(let i = 0; i < res.data.length; i++){
      //   res.data[i].title = res.data[i].menuName
      //   res.data[i].expand = true
      //   if(res.data[i].children){
      //     for(let j = 0; j < res.data[i].children.length; j++){
      //       res.data[i].children[j].title = res.data[i].children[j].menuName
      //     }
      //   }
      // }
      
    },
    //保存角色设置
    async saveRole(id){
      // console.log(this.AllAuthority)
      let checkID = []
      for(let i = 0; i < this.AllAuthority.length; i++){
        let tag = false
        if(this.AllAuthority[i].children){
          for(let j = 0; j < this.AllAuthority[i].children.length; j++){
            if(this.AllAuthority[i].children[j].checked){
              tag = true
              checkID.push(this.AllAuthority[i].children[j].id)
            }
          }
        }
        if(tag){
          checkID.push(this.AllAuthority[i].id)
        }
      }
      this.roleInfo.authorities = checkID
      const {data:res} = await this.$axios.post('/role/update', this.roleInfo)
      // console.log(res)
      if(res.status == 200){
        this.$Message.info('修改成功');
        this.$router.push('/admin/role')
      }else{
        this.$Message.info('修改失败');
      }
    }
  }
}
</script>

<style>
  #editRole{
    margin:0 2vw;
  }
  h3{
    margin:1vh 0;
  }
  .node{
    margin-bottom:12px;
  }
  .children{
    margin-left:18px;
  }
</style>